import os, sys
from urllib.parse import quote_plus
from urllib.request import urlopen
from urllib.request import Request
from urllib.parse import urlencode
from urllib.error import URLError
try:
    from PIL import Image
except:
    os.system("pip3 install pillow")
import base64
import json
import ssl
import io

ssl._create_default_https_context = ssl._create_unverified_context

def fetch_token():
    params = {'grant_type': 'client_credentials',
              'client_id': main.API_KEY,
              'client_secret': main.SECRET_KEY}
    post_data = urlencode(params)
    post_data = post_data.encode('utf-8')
    req = Request(main.TOKEN_URL, post_data)
    try:
        f = urlopen(req, timeout=5)
        result_str = f.read()
    except URLError as err:
        print(err)
    result_str = result_str.decode()

    result = json.loads(result_str)

    if ('access_token' in result.keys() and 'scope' in result.keys()):
        if not 'brain_all_scope' in result['scope'].split(' '):
            print ('please ensure has check the  ability')
            exit()
        return result['access_token']
    else:
        print ('please overwrite the correct main.API_KEY and main.SECRET_KEY')
        exit()

def read_file(image_path):
    f = None
    try:
        f = open(image_path, 'rb')
        return f.read()
    except:
        print('read image file fail')
        return None
    finally:
        if f:
            f.close()

def request(url, data):
    req = Request(url, data.encode('utf-8'))
    has_error = False
    try:
        f = urlopen(req)
        result_str = f.read()
        result_str = result_str.decode()
        return result_str
    except  URLError as err:
        print(err)

def main(a):

    image_url = main.OCR_URL + "?access_token=" + main.token
    text = ""
    file_read = read_file(a)
    result = request(image_url, urlencode({'image': base64.b64encode(file_read)}))
    result_dict = json.loads(result)
    open(os.path.basename(a).rsplit(".")[0]+".txt", 'w', encoding='utf8').write(result)


def main2(a):

    if os.path.isdir(a):
        for i in os.listdir(a):
            main(os.path.join(a, i))
    else:
        main(a)

'''
[token?]("to clear what is token")
#[[request]:](json*)
a*表示a的位置（范围）
'''

if __name__ == '__main__':
    #main.OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic" #标准
    main.OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/general" #标准位置
    #main.OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic" #高精度
    #main.OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate" #高精度位置
    main.TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'

    try:
        main.API_KEY = os.environ['API_KEY_3gy6']
        main.SECRET_KEY = os.environ['SECRET_KEY_3gy6']
        main.token = fetch_token()
        is_env = True
    except:
        print("\tYou may set API_KEY_3gy6 and SECRET_KEY_3gy6")
        is_env = False
    if is_env:
        if len(sys.argv) <=1:
            print("\tpython *this [*picture]...")
            sys.exit(0)
        for i in sys.argv[1:]:
            main2(i.strip('\'\"\\').rstrip("/"))
    else:
        if len(sys.argv) <=3:
            print("\tpython *this [*API_KEY] [*SECRET_KEY] [*picture]...")
            sys.exit(0)
        main.API_KEY = sys.argv[1]
        main.SECRET_KEY = sys.argv[2]
        main.token = fetch_token()
        for i in sys.argv[3:]:
            main2(i.strip('\'\"\\').rstrip("/"))
